package com.sc.smartcommunity.controller;

import com.sc.smartcommunity.common.Result;
import com.sc.smartcommunity.minio.MinioUtils;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Chenke Zhao
 * @date 2025/9/13 16:28
 * @description FileController
 */
@RestController
@RequestMapping("/file")
public class FileController {


    @Autowired
    private MinioUtils minioUtils;

    @PostMapping("/upload")
    @Operation(summary = "文件上传", description = "用户上传文件到 MinIO 存储")
    public Result testUpload(MultipartFile file) throws Exception {
        minioUtils.uploadFile("my-bucket", file.getOriginalFilename(), file.getInputStream(), file.getSize(), file.getContentType());
        String url = minioUtils.getFileUrl("my-bucket", file.getOriginalFilename());
        System.out.println("文件访问链接: " + url);
        return Result.success(url);
    }

    @PostMapping("/uploadBatch")
    @Operation(summary = "批量文件上传", description = "用户批量上传文件到 MinIO 存储")
    public Result uploadBatch(@RequestParam("files") MultipartFile[] files) throws Exception {
        String bucket = "my-bucket";
        StringBuilder urls = new StringBuilder();

        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            if (!file.isEmpty()) {
                // 上传文件
                minioUtils.uploadFile(bucket,
                        file.getOriginalFilename(),
                        file.getInputStream(),
                        file.getSize(),
                        file.getContentType());

                // 获取文件访问链接
                String url = minioUtils.getFileUrl(bucket, file.getOriginalFilename());

                urls.append(url);
                if (i < files.length - 1) {
                    urls.append(",");
                }
            }
        }

        System.out.println("批量上传文件访问链接: " + urls);
        return Result.success(urls.toString());
    }

}
